﻿<?php
require_once "db.class.php";
require_once "config.php";
require_once "handler/actionHandler.php";

function generateSig($params_array, $secret)
{
	$str = "";
	ksort($params_array);
	foreach ($params_array as $k=>$v)
	{
		if ($k != "xn_sig" && $k != "b2Sig")
		{
			$str .= "$k=$v";
//				$str = str_replace("\\", "", $str);
		}
	}
	$str .= $secret;
	return md5($str);
}

//MD5验证，是否B2客户端发起
if (generateSig($_POST, $secret) != $_POST['b2Sig'])
{
	//$debug2 = $server->generate_sig($_POST, $secret)." <-> ".$_POST['b2Sig'];
	die();
}

$params = array("host"=>"$host", "user"=>"$user", "pass"=>"$pass", "db"=>"$db");
$db = new Dbclass($params, false);

$jsonString=urldecode($_POST['json']);
$jsonString=str_replace("//","",$jsonString);
$jsonData=json_decode($jsonString,true);

$microtimestamp = microtime(true);
$action = $jsonData['action'];
$userId = $jsonData['userId'];
$sessionId = $jsonData['sessionId'];
$callId = $jsonData['callId'];
$content = "";
$res = 0;
$debug = "";

//登陆
if ($action != 'login')
{
	//检查session
	$sql = "select count(*) as num from ".$tb_user_profile." where id = ".$userId." and sessionId = '".$sessionId."'";
	$result = $db->query($sql);
	$arr = $db->fetchArray($result);
	if ($arr['num'] <= 0)
	{
		$res = 100;
	}
	else
	{
		//检查callId
		$sql = "insert into ".$tb_user_call." (ownerId, callId) values (".$userId.", ".$callId.")";
		$result = $db->query($sql);
		$sql = "select count(*) as num from ".$tb_user_call." where ownerId = ".$userId." and callId = ".$callId;
		$result = $db->query($sql);
		$arr = $db->fetchArray($result);
		if ($arr['num'] > 1)
		{
			$res = 101;
		}
	}
}
if ($res == 0)
{
	if ($action_map[$action])
	{
		require_once $action_map[$action];
		$handler = new $action($db, $tables);
		$content = $handler->handleRequest($jsonData);
		$debug .= $handler->debug;
	}
}

$db->close();

$phpElapsedTime = (microtime(true) - $microTimeStamp) * 1000;

$response = array();
$response["debug"] = $debug;
$response["action"] = $action;
$response["res"] = $res;
$response["timeStamp"] = $timeStamp;
$response["phpElapsedTime"] = $phpElapsedTime;
$response["data"] = $content;
$txt = json_encode($response);

echo $txt;

?>
